<template>
  <uni-popup ref="popupPay" type="bottom" :safe-area="false" :mask-click="false">
    <view class="pay-panel">
      <view class="price-container" v-if="mode">
        <view class="title">{{ product && product.title }}</view>
        支付金额：
        <view class="unit">￥</view>
        <view class="price">{{ mode === 'order' ? order.wantFee / 100 : product.price }}</view>
      </view>
      <template v-if="channels.length">
        <view :class="['channel', item.code]" @click="select(item)" v-for="(item, index) in channels"
              :key="item.code">
          <view class="icon"></view>
          <view class="label">{{ item.label }}</view>
          <view v-if="item.disable">{{ item.disable }}</view>
          <radio :value="item.code" :checked="item.code === channel.code" v-else color="#1B2229"
                 style="transform:scale(0.7)"/>
        </view>
      </template>
      <view class="channel" v-else>
        <view class="label">没有可用支付渠道</view>
      </view>
      <view class="flex">
        <view class="btn" @click="dismiss">再想想</view>
        <view class="btn pay" @click="toPay">确定支付</view>
      </view>
    </view>
  </uni-popup>
</template>

<script>
import {
  mapGetters,
  mapActions
} from 'vuex'
import {
  orderApi
} from '@/api.js'
import payUtils from "@/libs/payUtils.js";

export default {
  name: "pay",
  data() {
    return {
      channel: null,
      channels: [],
      product: null,
      order: null,
      from: null,
      mode: null,
    };
  },
  beforeDestroy() {
    this.clearPollOrderHandler()
  },
  computed: {
    ...mapGetters(['mine']),
  },
  created() {

  },
  methods: {
    ...mapActions(['refreshUser']),
    open({mode, product, order, from}) {
      if (mode === 'product') {
        this.product = product
        this.mode = mode
        this.from = from
      } else if (mode === 'order') {
        this.order = order
        this.mode = mode
        this.from = from
      } else {
        console.error('mode', mode)
        return
      }
      payUtils.init().then(() => {
        let {
          channels,
          channel
        } = payUtils.getChannels({needVirtual: mode === 'product' ? product.iosProductId : order.iosProductId})
        // const {channels, channel} = payUtils.getChannels({})
        console.log('channels', channels, channel)

        if (this.mine.dev) {
          channel = {
            code: 'test',
            label: '测试支付，id：' + this.mine.id
          }
          channels.push(channel)
        } else {
          const wx = channels.find(channel => channel.code === 'wxpay')
          const ali = channels.find(channel => channel.code === 'alipay')
          // console.log('wx, ali', wx, ali)

          if (wx) {
            channels = [wx]
            channel = wx
          } else if (ali) {
            channels = [ali]
            channel = ali
          } else {

          }
        }
        this.channels = channels
        // this.channels = [channels[0]]
        this.channel = channel

        if (!this.mine.dev && this.channels.length === 1) {
          this.toPay('noUI')
        } else {
          this.$refs.popupPay.open()
        }
      })
    },
    async toPay(mode) {
      if (!this.channel) {
        return uni.showToast({
          title: '请选择支付渠道',
          icon: 'none',
          duration: 2000
        });
      }

      if (this.channel.message) {
        return uni.showToast({
          title: this.channel.message,
          icon: 'none',
          duration: 2000
        });
      }
      await this.refreshUser()
      let orderId;
      try {
        orderId = await payUtils.toPay({
          channelCode: this.channel.code,
          mode: this.mode,
          order: this.order,
          product: this.product,
        })
      } catch (e) {
        uni.hideLoading()
        uni.showToast({
          title: e.message || '支付异常，稍后再试',
          icon: 'none',
          duration: 2000
        });

        if (mode === 'noUI') {
          this.dismiss()
        }
        return
      }
      this.$refs.popupPay.close()

      await this.startPollOrder(orderId)
      uni.showToast({
        icon: 'success',
        duration: 2000,
        title: '支付成功！'
      })

      this.$emit('success', {mode: this.mode, from: this.from, product: this.product, order: this.order})
    },

    clearPollOrderHandler() {
      if (this._pollOrderHandler) {
        clearInterval(this._pollOrderHandler)
        this._pollOrderHandler = null
      }
    },
    startPollOrder(orderId) {
      console.log('startPollOrder', orderId)
      let index = 1
      uni.showLoading({
        title: '等待支付结果' + index,
        mask: true
      })
      return new Promise(resolve => {
        this._pollOrderHandler = setInterval(async () => {
          index++
          uni.showLoading({
            title: '等待支付结果' + index,
            mask: true
          })
          try {
            await orderApi.pollSuccess(orderId)
            this.clearPollOrderHandler()
            console.log('支付成功服务端回调')
            resolve()
          } catch (e) {
            console.log('支付还没成功！', e)
          }
        }, 1000)
      })
    },

    dismiss() {
      this.product = null
      this.order = null
      this.mode = null
      this.from = null
      uni.showTabBar();
      this.$emit('dismiss')
      this.$refs.popupPay.close()
    },
    select(channel) {
      if (channel.disable) {
        return
      }

      this.channel = channel
      console.log(channel)
    }
  }
}
</script>

<style lang="scss">
.pay-panel {
  background-color: #fff;
  padding: 0 36upx;
  box-sizing: border-box;

  .price-container {
    height: 146upx;
    display: flex;
    align-items: center;
    font-size: 26upx;
    font-weight: 500;
    color: #505050;
    border-bottom: 1px solid #00000014;

    .title {
      flex: 1;
      font-size: 32upx;
    }

    .price {
      font-size: 48upx;
      color: #1b2229;
      margin-bottom: 10upx;
    }

    .unit {
      color: #1b2229;
    }
  }

  .channel {
    height: 112upx;
    border-bottom: 1px solid #00000014;
    display: flex;
    align-items: center;
    font-size: 32upx;

    .icon {
      width: 32upx;
      height: 32upx;
      background-size: contain;
      background-position: center;
      background-repeat: no-repeat;
      margin-right: 32upx;
    }

    &.alipay {
      .icon {
        background-image: url(@/static/pay_ali@3x.png);
      }
    }

    &.toutiao {
      .icon {
        background-image: url(@/static/login/toutiao.png);
        background-color: #0C0C18;
        border-radius: 3px;
      }
    }

    &.appleiap {
      .icon {
        background-image: url(@/static/login/pingguo.png);
        background-color: #000;
        border-radius: 3px;
      }
    }

    &.wxpay {
      .icon {
        background-image: url(@/static/pay_wx@3x.png);
      }
    }

    .label {
      flex: 1;
    }
  }

  .btn {
    height: 94upx;
    flex: 1;
    display: flex;
    background-color: #f3f3f3;
    justify-content: center;
    align-items: center;
    border-radius: 12upx;
    color: #1b1b1b;
    font-size: 30upx;
    margin-top: 68upx;
    margin-bottom: 76upx;

    &.pay {
      margin-left: 30upx;
      background-color: #E3C898;
      color: #1E252D;
      font-weight: 500;
    }
  }
}
</style>
